﻿using System;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading;
using System.Collections.Generic;
using BaseUtils.Logger;
using DriveManage.SocketClient;
using BaseUtils;

namespace DriveManage.Tcp.Server
{

    //// 定义一个委托，用于处理客户端连接事件的回调
    //public delegate void ClientConnectedEventHandler(TcpClient client);
    //// 定义一个委托，用于处理客户端断开连接事件的回调
    //public delegate void ClientDisconnectedEventHandler(TcpClient client);
    //// 定义一个委托，用于处理接收到客户端消息事件的回调
    //public delegate void MessageReceivedEventHandler(TcpClient client, string message);

    public class SocketServerManager : ISocketHandler
    {

        private int _Port = 6677; // 默认端口
        private string _Rerminator = null; // 结束符号

        private TcpListener Server;
        private List<TcpClient> _ConnectedClients = new List<TcpClient>();
        public StringBuilder _ReceiveDataCache = new StringBuilder();
        public StringBuilder ReceiveDataCache => _ReceiveDataCache;
        public List<TcpClient> ConnectedClients => _ConnectedClients;
        public bool IsConnected => true;

        public string Terminal => _Terminal;
        public string _Terminal = "";

        // 客户端连接事件的回调
        public event ClientConnectedEventHandler OnClientConnected;
        // 客户端断开连接事件的回调
        public event ClientDisconnectedEventHandler OnClientDisconnected;
        // 接收到客户端消息事件的回调
        public event MessageReceivedEventHandler OnMessageReceived;
        public event OnConnectedHandler OnConnected;
        public event OnConnectedHandler OnFaildConnect;
        public event OnReceiveMsgHandler OnReceiveMsg;
        public event ConnectErrorHandler OnConnectError;

        public SocketServerManager(int Port, string Rerminator = null)
        {
            if (!string.IsNullOrEmpty(Rerminator))
            {
                _Rerminator = Rerminator;
            }
            _Terminal = "server";
            _Port = Port;
            Server = new TcpListener(IPAddress.Any, Port);
        }

        /// <summary>
        /// 启动服务
        /// </summary>
        public bool Start()
        {
            try
            {
                // 创建 TcpListener 实例，监听所有可用的网络接口和指定端口
                // server = new TcpListener(IPAddress.Any, Port);
                // 启动服务器
                _ReceiveDataCache.Clear();
                Server.Start();
                LoggerService.Info($"服务启动成功，端口：{_Port}");

                Thread ne = new Thread(() => OnTcpClient());
                ne.Start();
            }
            catch (Exception ex)
            {
                // 捕获并输出异常信息
                LoggerService.Error($"服务启动失败，端口：{_Port}，原因：{ex.Message}", ex);
                Stop();
            }
            finally
            {
                // _ReceiveDataCache.Clear();
            }

            return true;
        }

        /// <summary>
        /// 停止服务
        /// </summary>
        /// <returns></returns>
        public bool Stop()
        {
            LoggerService.Info($"正在停止服务，端口：{_Port}");
            try
            {
                _ReceiveDataCache.Clear();
                // 停止服务器监听
                Server.Stop();
                // 关闭所有连接的客户端
                lock (_ConnectedClients)
                {
                    foreach (var client in _ConnectedClients)
                    {
                        client.Close();
                    }
                    _ConnectedClients.Clear();
                    LoggerService.Info($"正在停止服务，端口：{_Port}");
                }
                return true;
            }
            catch (Exception ex)
            {
                LoggerService.Error($"服务停止失败，端口：{_Port}，原因：{ex.Message}", ex);
                return false;
            }
        }

        /// <summary>
        ///  监听客户端的连接
        /// </summary>
        private void OnTcpClient()
        {
            // 持续监听客户端连接
            while (true)
            {
                try
                {
                    // 等待客户端连接，接受连接后返回一个 TcpClient 实例
                    TcpClient client = Server.AcceptTcpClient();
                    // 将新连接的客户端添加到客户端列表中
                    lock (_ConnectedClients)
                    {
                        _ConnectedClients.Add(client);
                    }
                    string ClientAddress = ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString();
                    LoggerService.Error($"客户端连接成功，端口：{_Port}，客户端IP={ClientAddress}");
                    // 触发客户端连接事件的回调
                    OnClientConnected?.Invoke(client);

                    // 为每个客户端连接创建一个新的线程来处理
                    Thread clientThread = new Thread(() => HandleClient(client));
                    clientThread.Start();
                }
                catch (Exception ex)
                {
                    LoggerService.Error($"客户端连接失败，端口：{_Port}，原因：{ex.Message}", ex);
                }
            }
        }

        /// <summary>
        /// 检查是否有客户端连接
        /// </summary>
        /// <returns>如果有客户端连接返回 true，否则返回 false</returns>
        public bool HasConnectedClients()
        {
            lock (_ConnectedClients)
            {
                return _ConnectedClients.Count > 0;
            }
        }

        /// <summary>
        /// 处理客户端连接
        /// </summary>
        /// <param name="client">客户端连接</param>
        private void HandleClient(TcpClient client)
        {
            NetworkStream stream = null;
            try
            {
                int BufferSize = 4096;
                if (BaseService.AppConfig.field.BufferSize > 0) {
                    BufferSize = BaseService.AppConfig.field.BufferSize;
                    LoggerService.Info($"接收缓存区大小：{BufferSize}");
                }
                stream = client.GetStream();
                byte[] buffer = new byte[BufferSize];
                int bytesRead;

                // 持续从客户端接收数据
                while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    // 将接收到的字节数组转换为字符串
                    // 触发接收到客户端消息事件的回调
                    string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                    LoggerService.Info($"收到客户端数据：{message}");
                    //if (!string.IsNullOrEmpty(_Rerminator))
                    if (false)
                    {
                        bool IsRerminator = message.Contains(_Rerminator);
                        message = message.Replace(_Rerminator, "");
                        AddDataCache(message);
                        if (IsRerminator)
                        {
                            //Callback(client);
                        }
                    }
                    else
                    {
                        AddDataCache(message);
                        //OnMessageReceived?.Invoke(this, client, message);
                        Callback(client, buffer);
                    }
                }
                // 当 Read 方法返回 0 时，表示客户端正常关闭连接
                LoggerService.Warning($"Client disconnected normally.");
            }
            catch (SocketException ex) when (ex.SocketErrorCode == SocketError.ConnectionReset)
            {
                LoggerService.Warning($"Client disconnected abruptly.", ex);
            }
            catch (Exception ex)
            {
                LoggerService.Warning($"Error handling client: {ex.Message}", ex);
            }
            finally
            {
                // 从客户端列表中移除断开连接的客户端
                lock (_ConnectedClients)
                {
                    _ConnectedClients.Remove(client);
                }
                // 触发客户端断开连接事件的回调
                OnClientDisconnected?.Invoke(client);
                stream?.Close();
                client?.Close();
            }
        }

        private void Callback(TcpClient client, byte[] buffer)
        {
            OnMessageReceived?.Invoke(this, client, buffer, _ReceiveDataCache.ToString());
            _ReceiveDataCache.Clear();
        }

        private void AddDataCache(string msg)
        {
            _ReceiveDataCache.Append(msg);
            //_ReceiveDataCache.Add(msg);
            //if (_ReceiveDataCache?.Count > 100000)
            //{
            //    _ReceiveDataCache.RemoveRange(_ReceiveDataCache.Count - 5000, 5000);
            //}
        }

        /// <summary>
        /// 向指定客户端发送消息
        /// </summary>
        /// <param name="Stream">客户端连接</param>
        /// <param name="ResponseMessage">要发送的消息</param>
        public void SendMessage(TcpClient Client, string ResponseMessage)
        {
            try
            {
                NetworkStream Stream = Client.GetStream();
                byte[] responseBuffer = Encoding.UTF8.GetBytes(ResponseMessage);
                Stream.Write(responseBuffer, 0, responseBuffer.Length);
                LoggerService.Info($"发送消息给客户端：{ResponseMessage}");
            }
            catch (Exception ex)
            {
                LoggerService.Info($"发送消息给客户端失败：{ResponseMessage}，原因：{ex.Message}", ex);
            }
        }

        /// <summary>
        /// 向所有连接的客户端发送消息
        /// </summary>
        /// <param name="message">要发送的消息</param>
        public void SendMessage(string message)
        {
            if (!string.IsNullOrEmpty(_Rerminator))
            {
                message += _Rerminator;
            }
            lock (_ConnectedClients)
            {
                foreach (var client in _ConnectedClients)
                {
                    SendMessage(client, message);
                }
            }
        }

        public void Disconnect()
        {
        }

        public void StartReconnect()
        {
        }
    }
}
